<?php
/**
 * http客户端
 * **/

class Tools_HttpClient
{
	
	private $result = array('output'        => "",
					        'httpCode'      => "",
							'requestHeader' => "",
							'responseHead'  => "",
							'error'         => "");
	/**
	 * 初始化方法
	 * **/
	function __construct(){}
	
	/**
	 * http请求
	 * @return array('httpCode'=>"http状态码",'output'=>"返回信息",'error'=>"错误信息",'requestHeader'=>"请求头");
	 * **/
	function request($url,$data = null,$heads = array("User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"))
	{
		$ch   = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HEADER, $heads);
		curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

		if(!empty($data))
		{
			@curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
			curl_setopt($ch, CURLOPT_POST, 1);
		}
			
		$result['output']         = curl_exec($ch);
		$result['httpCode']       = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		$result['requestHeader']  = curl_getinfo($ch, CURLINFO_HEADER_OUT);
		$result['error']          = curl_error($ch);
		$headerSize               = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
		$result['responseHead']   = substr($result['output'], 0, $headerSize);
		$result['output']         = substr($result['output'], $headerSize);
		
		curl_close($ch);
		
		return $result;
	}
	
	/**
	 * 下载文件
	 * **/
	function requestFile($url,$file_name)
	{
		$result = $this->request($url);
		$tmp    = $result["output"];
		$size=strlen($tmp);
		//文件大小
		$fp2=@fopen($file_name,'a');
		fwrite($fp2,$tmp);
		fclose($fp2);
	}

}